from typing import Dict, List
from PyQt6.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QWidget,
    QScrollArea,
)


class EnvVarDialog(QDialog):
    """一次性填写多个环境变量的对话框

    使用示例:
        dlg = EnvVarDialog(['IDF_TARGET', 'IDF_PATH'])
        if dlg.exec() == QDialog.DialogCode.Accepted:
            values = dlg.get_values()
    """

    def __init__(self, vars: List[str], parent: QWidget | None = None):
        super().__init__(parent)
        self.setWindowTitle('Provide missing Kconfig environment variables')
        self._vars = vars
        self._edits: Dict[str, QLineEdit] = {}

        self._init_ui()

    def _init_ui(self):
        layout = QVBoxLayout(self)

        info = QLabel("The parser reported missing environment variables. Please provide values:")
        layout.addWidget(info)

        # scroll area in case there are many
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        container = QWidget()
        container_layout = QVBoxLayout(container)

        for v in self._vars:
            row = QHBoxLayout()
            lbl = QLabel(v)
            edit = QLineEdit()
            edit.setPlaceholderText(f'Value for {v}')
            row.addWidget(lbl)
            row.addWidget(edit)
            container_layout.addLayout(row)
            self._edits[v] = edit

        scroll.setWidget(container)
        layout.addWidget(scroll)

        btn_row = QHBoxLayout()
        ok = QPushButton('Save and Retry')
        cancel = QPushButton('Cancel')
        btn_row.addStretch()
        btn_row.addWidget(cancel)
        btn_row.addWidget(ok)
        layout.addLayout(btn_row)

        ok.clicked.connect(self.accept)
        cancel.clicked.connect(self.reject)

    def get_values(self) -> Dict[str, str]:
        out: Dict[str, str] = {}
        for k, edit in self._edits.items():
            v = edit.text().strip()
            if v:
                out[k] = v
        return out
